package org.example.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author chaigq
 * @version 1.0
 * @date 2022/3/23 1:58 下午
 */
public class ThreadUnsafeExample {

    private int count = 0;
    public void add(){
        count ++;
    }

    public int get(){
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        final int threadCount = 1000;
        ThreadUnsafeExample threadUnsafeExample = new ThreadUnsafeExample();
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            executorService.execute(() -> {
                threadUnsafeExample.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(threadUnsafeExample.get());
    }
}












